package com.cms.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.entity.Category;
import com.cms.entity.Content;
import com.cms.enums.ContentStatus;
import com.cms.mapper.ContentMapper;
import com.cms.utils.DbUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 内容表 服务实现类
 * </p>
 *
 * @author songfayuan
 * @since 2021-11-12
 */
@Service
public class ContentService extends ServiceImpl<ContentMapper, Content> {

    @Autowired
    private CategoryService categoryService;


    /**
     * 根据编码获取内容
     * @return	内容
     */
    public Content findByCode(String code,Integer siteId){
        QueryWrapper<Content> queryWrapper = new QueryWrapper();
        queryWrapper.eq("code",code);
        queryWrapper.eq("siteId",siteId);
        return baseMapper.selectOne(queryWrapper);
    }


    /**
     * 检查code唯一
     *
     * @param code
     * @param id
     * @return
     */
    public boolean checkCode(String code,Integer id,Integer siteId){
        if(StringUtils.isBlank(code)){
            return true;
        }
        if(id!=null){
            Content content = getById(id);
            if(content.getCode().equals(code)){
                return true;
            }
        }
        Content content = findByCode(code,siteId);
        return content==null;
    }

    /**
     * 查找内容分页
     *
     * @param categoryId
     *            栏目ID
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页记录数
     * @return 内容分页
     */
    public Page<Content> findPage(Integer categoryId, String title, Integer pageNumber, Integer pageSize, Integer siteId){
        String filterSql = " and siteId="+siteId;
        if(categoryId!=null){
            filterSql+=" and (categoryId="+categoryId+" or categoryId in ( select id from cms_category where treePath  like '%"+Category.TREE_PATH_SEPARATOR+categoryId+Category.TREE_PATH_SEPARATOR+"%'))";
        }
        if(StringUtils.isNotBlank(title)){
            filterSql+= " and title like '%"+title+"%'";
        }
        String orderBySql = DbUtils.getOrderBySql("sort desc,createDate desc");
        Page<Map<String,Object>> page = SqlRunner.db().selectPage(new Page<>(pageNumber, pageSize),"select * from cms_content where 1=1 "+filterSql+orderBySql);
        Page<Content> newPage = new Page<>(pageNumber, pageSize);
        List<Content> newRecords = page.getRecords().stream().map(i-> JSON.parseObject(JSON.toJSONString(i), Content.class)).collect(Collectors.toList());
        newPage.setRecords(newRecords);
        return newPage;
    }


    /**
     * 查找内容分页
     *
     * @param categoryId
     *            栏目ID
     * @param categoryCode
     *            栏目编码
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页记录数
     * @return 内容分页
     */
    public Page<Content> findPage(Integer categoryId,String categoryCode,Integer tagId,String keyword,String condition,String orderBy,Integer pageNumber,Integer pageSize,Integer siteId){
        String filterSql = " and siteId="+siteId+" and status="+ ContentStatus.NORMAL.ordinal();
        if(categoryId!=null || StringUtils.isNotBlank(categoryCode)){
            if(categoryId==null && StringUtils.isNotBlank(categoryCode)){
                Category category = categoryService.findByCode(categoryCode,siteId);
                categoryId = category.getId();
            }
            filterSql+=" and (categoryId="+categoryId+" or categoryId in ( select id from cms_category where treePath  like '%"+Category.TREE_PATH_SEPARATOR+categoryId+Category.TREE_PATH_SEPARATOR+"%'))";
        }
        if(tagId!=null){
            filterSql+= " and tagIdValue like '%,"+tagId+",%'";
        }
        if(StringUtils.isNotBlank(condition)){
            filterSql+=" and "+condition;
        }
        if(StringUtils.isNotBlank(keyword)){
            filterSql+= " and title like '%"+keyword+"%'";
        }
        String orderBySql = "";
        if(StringUtils.isBlank(orderBy)){
            orderBySql = DbUtils.getOrderBySql("sort desc,createDate desc");
        }else{
            orderBySql = DbUtils.getOrderBySql(orderBy+",sort desc");
        }
        Page<Map<String,Object>> page = SqlRunner.db().selectPage(new Page<>(pageNumber, pageSize),"select * from cms_content where 1=1 "+filterSql+orderBySql);
        Page<Content> newPage = new Page<>(pageNumber, pageSize);
        List<Content> newRecords = page.getRecords().stream().map(i-> JSON.parseObject(JSON.toJSONString(i), Content.class)).collect(Collectors.toList());
        newPage.setRecords(newRecords);
        return newPage;
    }

    /**
     * 查找内容
     *
     * @param categoryId
     *            栏目ID
     * @param categoryCode
     *            栏目编码
     * @param orderBy
     *            排序
     * @param start
     *            起始位置
     * @param count
     *            数量
     * @return 内容
     */
    public List<Content> findList(Integer categoryId, String categoryCode,String condition, Date startDate, Date endDate, String orderBy, Integer start, Integer count, Integer siteId){
        String filterSql = " and siteId="+siteId+" and status="+ ContentStatus.NORMAL.ordinal();
        if(categoryId!=null || StringUtils.isNotBlank(categoryCode)){
            if(categoryId==null && StringUtils.isNotBlank(categoryCode)){
                Category category = categoryService.findByCode(categoryCode,siteId);
                categoryId = category.getId();
            }
            filterSql+=" and (categoryId="+categoryId+" or categoryId in ( select id from cms_category where treePath  like '%"+Category.TREE_PATH_SEPARATOR+categoryId+Category.TREE_PATH_SEPARATOR+"%'))";
        }
        if(StringUtils.isNotBlank(condition)){
            filterSql+=" and "+condition;
        }
        if(startDate!=null){
            filterSql=" and createDate>='"+ DateFormatUtils.format(startDate, "yyyy-MM-dd HH:mm:ss")+"'";
        }
        if(endDate!=null){
            filterSql=" and createDate<='"+DateFormatUtils.format(endDate, "yyyy-MM-dd HH:mm:ss")+"'";
        }
        String orderBySql = "";
        if(StringUtils.isBlank(orderBy)){
            orderBySql = DbUtils.getOrderBySql("sort desc,createDate desc");
        }else{
            orderBySql = DbUtils.getOrderBySql(orderBy+",sort desc");
        }
        String countSql=DbUtils.getCountSql(start, count);
        List<Map<String,Object>> contents = SqlRunner.db().selectList("select * from cms_content where 1=1 "+filterSql+orderBySql+countSql);
        return contents.stream().map(i-> JSON.parseObject(JSON.toJSONString(i), Content.class)).collect(Collectors.toList());
    }

}
